<?php
/**
 * @author vinhnv@vnext.vn
 * @version 1.0
 * @package Fdoc
 * @subpackage FdocSystem
 *
 */
class Vlib_Common {

	/**
	 * instance object FdocCommon
	 *
	 * @var FdocCommon
	 */
	private static $_instance = null;

	/**
	 * Constructor method
	 *
	 */
	private function __construct(){

	}

	/**
	 * get Instance class
	 *
	 * @return FdocCommon
	 */
	public static function getInstance() {
		if (!isset(self::$_instance)) {
			$cls = __CLASS__;
			self::$_instance = new $cls();
		}
		return self::$_instance;
	}


	/**
	 * calculateDateRange
	 * Calculate date range to display schedule
	 * $date: Base date - Y-m-d
	 * $rangeType: 1: week; 2: month (42 days)
	 * $startDate: start date of range
	 * $endDate: end date of range
	 * $weekStartDate: only use when $rangeType = 1, value on 0:Monday-6:Sunday
	 * $format: display format of $startDate and $endDate
	 *
	 * @param Date $date
	 * @param Integer $rangeType
	 * @param Date $startDate
	 * @param Date $endDate
	 * @param Integer $weekStartDate
	 * @param String $format
	 */
	public function calculateDateRange($date, $rangeType, &$startDate, &$endDate, $weekStartDate = 0, $format = 'Y-m-d') {
		if($rangeType == 1) {
			$aryDayOfWeek = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
			$currentDayOfWeek = (int)date('N', strtotime($date)) - 1;
			/* DUngbq sua lai trong truong hop thiet dinh la today */
			if(($weekStartDate >= 7) || ($weekStartDate < 0) || ($weekStartDate == $currentDayOfWeek)) {
				$strCalDate = 'today';
			}
			else if($weekStartDate > $currentDayOfWeek) {
				//Modify by MinhNV 2007.12.03 fixbug 111
				//$strCalDate = 'next '.$aryDayOfWeek[$weekStartDate];
				$strCalDate = $aryDayOfWeek[$weekStartDate].'-1 week';
				//Modify by MinhNV 2007.12.03 fixbug 111
			}
			else {
				//Modify by MinhNV 2007.12.03 fixbug 111
				//$strCalDate = 'last '.$aryDayOfWeek[$weekStartDate];
				$strCalDate = $aryDayOfWeek[$weekStartDate].'-1 week';
				//Modify by MinhNV 2007.12.03 fixbug 111
			}

			$startDate = strtotime($strCalDate, strtotime($date));
			$endDate = strtotime('+ 6 days', $startDate);
		}
		else if($rangeType == 2) {

			$firstDayOfMonth = strtotime('first day', strtotime(date('Y-m', strtotime($date)) . '-01'));
			if((int)date('N', $firstDayOfMonth) > 1) {
				$startDate = strtotime('last Monday', $firstDayOfMonth);
			}
			else {
				$startDate = $firstDayOfMonth;
			}

			$endDate = strtotime('+ 41 days', $startDate);
		}
		else if($rangeType == 3) {
			$aryDayOfWeek = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
			$currentDayOfWeek = (int)date('N', strtotime($date)) - 1;
			/* DUngbq sua lai trong truong hop thiet dinh la today */
			if(($weekStartDate >= 7) || ($weekStartDate < 0) || ($weekStartDate == $currentDayOfWeek)) {
				$strCalDate = 'today';
			}
			else if($weekStartDate > $currentDayOfWeek) {
				//Modify by MinhNV 2007.12.03 fixbug 111
				//$strCalDate = 'next '.$aryDayOfWeek[$weekStartDate];
				$strCalDate = $aryDayOfWeek[$weekStartDate].'-2 week';
				//Modify by MinhNV 2007.12.03 fixbug 111
			}
			else {
				//Modify by MinhNV 2007.12.03 fixbug 111
				//$strCalDate = 'last '.$aryDayOfWeek[$weekStartDate];
				$strCalDate = $aryDayOfWeek[$weekStartDate].'-2 week';
				//Modify by MinhNV 2007.12.03 fixbug 111
			}

			$startDate = strtotime($strCalDate, strtotime($date));
			$endDate = strtotime('+ 13 days', $startDate);
		}

		$startDate = date($format, $startDate);
		$endDate = date($format, $endDate);
	}

	public function formatTime($time) {

		$timeFormated = '00:00';

		$pattern = '/^([0-9]{1,2})([:])([0-9]{1,2})$/';
		if(!preg_match($pattern, $time)) return $timeFormated;

		$aryTmp = explode(':', $time);// ThanhDH: use explode instead of split
		$timeFormated = strlen($aryTmp[0]) == 2 ? $aryTmp[0] : '0'.$aryTmp[0];
		$timeFormated .= ':';
		$timeFormated .= strlen($aryTmp[1]) == 2 ? $aryTmp[1] : '0'.$aryTmp[1];

		return $timeFormated;

	}

	/**
	 * check function existed
	 *
	 * @param string $funcName
	 * @param boolean $opt
	 * @return boolean
	 */
	public function hasFunc($funcName, $opt = true) {

		if (!function_exists($funcName)) {
			if ($opt) {
				throw new FdocException("Call to undefined function $funcName().");
			}
			else {
				return false;
			}
		}
		else {
			return true;
		}
	}

	/**
	 * convert encoding
	 *
	 * @param string $data
	 * @param string $toEncoding, to encoding
	 * @param string $fromEncoding, from encoding
	 * @return string
	 */
	public function convertEncoding($data, $toEncoding, $fromEncoding) {
		if(trim($data) == ""){
			return "";
		}

		$msg = $data;

		if (is_file(FDOC_ROOT_DIR . 'Packages/jcode_1.35a/jcode_wrapper.php') && in_array(strtoupper($toEncoding), array('SHIFT_JIS', 'SJIS', 'UTF-8', 'UTF-16LE', 'EUC-JP', 'ISO-2022-JP'))) {
			require_once FDOC_ROOT_DIR . 'Packages/jcode_1.35a/jcode_wrapper.php';// ThanhDH: changed require to require_once
			$msg = jcode_convert_encoding($data, $toEncoding, $fromEncoding);
		}
		if ($msg === $data) {
			self::hasFunc("mb_convert_encoding");
			$msg = @mb_convert_encoding($data, $toEncoding, $fromEncoding);
		}
		if ($msg === $data && self::unescape($data, $toEncoding)) {
			$msg = $data;
		}
		return $msg;
	}

	/**
	 * UCS-2 to Charset
	 *
	 * @param string $str
	 * @return string
	 */
	static function unescape(&$str, $toEncoding = 'UTF-8') {
		$str = rawurldecode($str);
		preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
		$ar = $r[0];

		$convertOK = true;
		foreach($ar as $k=>$v) {
			if(substr($v,0,2) == "%u") {
				if (!($ar[$k] = @iconv("UCS-2", $toEncoding,pack("H4",substr($v, -4))))) {
					$convertOK = false;
					break;
				}
			}
			elseif(substr($v,0,3) == "&#x") {
				if (!($ar[$k] = @iconv("UCS-2", $toEncoding,pack("H4",substr($v,3,-1))))) {
					$convertOK = false;
					break;
				}
			}
			elseif(substr($v,0,2) == "&#") {
				if (!($ar[$k] = @iconv("UCS-2", $toEncoding,pack("n",substr($v,2,-1))))) {
					$convertOK = false;
					break;
				}
			}
		}

		if ($convertOK) {
			$str = join('', $ar);
		}

		return $convertOK;
	}


	/**
	 * ShiftJIStoUTF8
	 * convert strings have encode are Shift_JIS to strings have encode are UTF-8
	 *
	 * @param string $str
	 * @param string $fromEncoding
	 * @return string, string after encoded
	 */
	public function ShiftJIStoUTF8($str, $fromEncoding = "SJIS,JIS,Shift_JIS,UTF-8") {
		return self::convertEncoding($str, "UTF-8", $fromEncoding);
	}

	/**
	 * UTF8toShiftJIS
	 * convert strings have encode are UTF-8 to strings have encode are Shift_JIS
	 *
	 * @param string $str
	 * @param string $fromEncoding
	 * @return string, string after encoded
	 */
	public function UTF8toShiftJIS($str, $fromEncoding = "UTF-8") {
		return self::convertEncoding($str, "Shift_JIS", $fromEncoding);
	}

	/**
	 * UTF8toUTF16LE
	 * convert strings have encode are UTF-8 to strings have encode are UTF-16LE
	 *
	 * @param string $str
	 * @param string $fromEncoding
	 * @return string, string after encoded
	 */
	public function UTF8toUTF16LE($str, $fromEncoding = "UTF-8") {
		return self::convertEncoding($str, "UTF-16LE", $fromEncoding);
	}
	/**
	 * UTF8toSJIS-Win
	 * convert strings have encode are UTF-8 to strings have encode are SJIS-Win
	 *
	 * @param string $str
	 * @param string $fromEncoding
	 * @return string, string after encoded
	 */
	public function UTF8toShiftWin($str, $fromEncoding = "UTF-8") {
		return self::convertEncoding($str, "SJIS-Win", $fromEncoding);
	}
	/**
	 * browser detect
	 *
	 * @return array
	 */
	public static function getUserBrowser() {
		$uAgent = $_SERVER['HTTP_USER_AGENT'];
		$ub = '';
		if(preg_match('/MSIE/i', $uAgent)) {
			$ub = "ie";
		}
		elseif(preg_match('/Firefox/i', $uAgent)) {
			$ub = "firefox";
		}
		elseif(preg_match('/Chrome/i', $uAgent)) {
			$ub = "chrome";
		}
		elseif(preg_match('/Safari/i', $uAgent)) {
			$ub = "safari";
		}
		elseif(preg_match('/Flock/i', $uAgent)) {
			$ub = "flock";
		}
		elseif(preg_match('/Opera/i', $uAgent)) {
			$ub = "opera";
		}

		// What version?
		$version = '';
        if (preg_match('/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/', $uAgent, $matches)) {
            $version = $matches[1];
        }

        // Running on what platform?
        $platform = '';
        if (preg_match('/linux/', $uAgent)) {
            $platform = 'linux';
        }
        elseif (preg_match('/macintosh|mac os x/', $uAgent)) {
            $platform = 'mac';
        }
        elseif (preg_match('/windows|win32/', $uAgent)) {
            $platform = 'windows';
        }

		return array('os' => $platform, 'browser' => $ub, 'ver' => $version);
	}

	/**
	 * Convert file name to download
	 *
	 * @param string $fileName
	 * @return string
	 */
	public static function convertFileNameToDownload($fileName) {
		$items = self::getUserBrowser();
		switch ($items['browser']) {
			case 'ie':
			case 'chrome':
				$fileName = self::UTF8toShiftJIS($fileName);
				break;

			case 'firefox':
			case 'safari':
			default:
				break;
		}
		return $fileName;
	}

	/**
	 * Paging
	 * @author PhongCT
	 * @param int $totalRecord
	 * @param int $recordPerPage
	 * @param int $pageId
	 * @param string $functionNameJs
	 * @param string $separator
	 * @param string $strPrev
	 * @param string $strNext
	 * @param string $strFirst
	 * @param string $strLast
	 * @return string
	 */
	public function paging(	$totalRecord, $recordPerPage, $pageId,	$functionNameJs,	$separator = '&nbsp;', $strPrev = 'Prev', $strNext = 'Next', $strFirst = '&laquo;',$strLast = '&raquo;')	{
		if ($recordPerPage == 0) {
			return "";
		}

		$st = "";
		if (strpos($url, '?') !== false) {
			$cc = '&';
		} else {
			$cc = '?';
		}

		$page_num = ceil($totalRecord / $recordPerPage) ;

		//$st .= ' / ' . $page_num . ' ';
		if (!(is_numeric($pageId) && ((int) $pageId == $pageId))) {
			$pageId = 1;
		}

		$pageId = (int) $pageId;

		if ($pageId < 1) {
			$pageId = 1;
		}

		if ($pageId > $page_num) {
			$pageId = $page_num;
		}

		if ($page_num < $page_range) {
			$page_range = $page_num;
		}

		if ($page_num >= 1) {

			if ($pageId - 1 == 0){
				$st .= " $strFirst ";
				$st.= " $strPrev ";
			}
			else {
					if (trim($strFirst)) $st .= " <a href='javascript:{$functionNameJs}(1)' id='page_first' >$strFirst</a> ";
					$st .= " <a href='javascript:{$functionNameJs}(" . ($pageId - 1) . ")' id='page_pre' >$strPrev</a> ";
			}

		}

		if ( $page_num >= 1) {
			if ($pageId + 1 > $page_num){
				$st .= " $strNext ";
				$st.= " $strLast ";
			}
			else{
				$st .= " <a href='javascript:{$functionNameJs}(" . ($pageId + 1) . ")' id = 'page_next' >$strNext</a> ";
				$st.= "<a href='javascript:{$functionNameJs}($page_num)' id = 'page_last' >$strLast</a> ";
			}
		}

		else{
			$st = "";
		}

		return $st;
	}

	/**
	 * split extension & namefile
	 *
	 * @param string $filename
	 * @return array $aryFileName
	 * 				 [0]: filename
	 * 				 [1]:  extension
	 * @author PhongCT
	 */

	function splitFileName($filename) {
		$filename = trim($filename);

		//$filename = strtolower($filename) ;
		$exts = explode('.', $filename) ;
		$aryFileName = array();

		if (count($exts) > 1) {
			$aryFileName[1] = trim($exts[count($exts)-1]);
			array_pop($exts);
		}
		else {
			$aryFileName[1] = '';
		}
		$aryFileName[0] = trim(@join('.', $exts));

		return $aryFileName;
	}
}
